//
//  File.swift
//  AIPhotoProcess
//
//  Created by aw031 on 17/10/2025.
//

import Foundation
import UIKit

extension String {
    
    func localizedString() -> String {
        // 获取用户设置的语言
//        let language = UserDefaults.standard.string(forKey: "KAppLocalizedLanguage") ?? ""
       let language = "en"
        // 如果语言为空，使用系统默认语言
        let languageCode = language.isEmpty ? "en" : language
        
        // 获取对应语言的 bundle 路径
        guard let bundlePath = Bundle.main.path(forResource: languageCode, ofType: "lproj"),
              let bundle = Bundle(path: bundlePath) else {
            // 如果找不到对应语言的 bundle，返回 key
            return self
        }
        
        // 获取本地化字符串
        let localizedString = bundle.localizedString(forKey: self, value: nil, table: "Localizable")
        
        // 检查字符串是否为空，如果为空则返回原始 key
        return KStringIsEmpty(localizedString) ? self : localizedString
    }

    
    /// 去除字符串前后空格
    func removeStartAndEndSpaces() -> String {
        return self.trimmingCharacters(in: .whitespaces)
    }

    /// 字符串宽高计算
    func calculateTextSize(constrainedTo size: CGSize, lineSpacing: CGFloat, font: UIFont) -> CGSize {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .paragraphStyle: paragraphStyle
        ]
        let rect = (self as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }

    /// 空字符串处理
    func emptyString() -> String {
        return self.isEmpty ? "" : self
    }

    /// 比较两个字符串内容（逗号分隔，顺序无关，数量相同）
    func isEqueToString(_ string: String) -> Bool {
        return String.isEqueToString(self, containsSameWordsAs: string)
    }

    static func isEqueToString(_ string1: String, containsSameWordsAs string2: String) -> Bool {
        if string1.isEmpty && string2.isEmpty { return true }
        if string1.isEmpty || string2.isEmpty { return false }
        if string1 == string2 { return true }
        let array1 = string1.split(separator: ",").map(String.init)
        let array2 = string2.split(separator: ",").map(String.init)
        if array1.count != array2.count { return false }
        let countedSet1 = NSCountedSet(array: array1)
        let countedSet2 = NSCountedSet(array: array2)
        return countedSet1 == countedSet2
    }
    
    //判断是不是单个字符串,并且是字母
    var isSingleEnglishLetter: Bool {
         guard count == 1, let char = first else { return false }
         return char.isLetter && char.isASCII
     }

    //判断字符串中是否含有字母
     func containsEnglishLetters() -> Bool {
        let pattern = "[a-zA-Z]"
        return self.range(of: pattern, options: .regularExpression) != nil
    }
    
    /// 检查两个字符串是否安全相等（空字符串视为相等）
    func StringSafeEqual(_ a: String?, _ b: String?) -> Bool {
        let isEmptyA = (a?.isEmpty ?? true)
        let isEmptyB = (b?.isEmpty ?? true)
        return (isEmptyA && isEmptyB) || a == b
    }

    func boundleImage(ofType: String?) -> String {
        
        let imagePath = Bundle.main.path(forResource: self, ofType: ofType)
        
        if let name = imagePath {
            
//            return name
            return "file://\(name)"
        }
        return ""
    }
    
    func imageAdd(ofType: String?) -> String {
        if KStringIsEmpty(self) {
            return ""
        }else {
            return "\(self).\(ofType!)"
        }
    }
    
    
    func withRedUnderline(font: UIFont? = nil,underlineColor:UIColor = Color7884AE) -> NSAttributedString {
          var attributes: [NSAttributedString.Key: Any] = [
              
            .underlineStyle: NSUnderlineStyle.single.rawValue,
                .underlineColor: underlineColor,
                .baselineOffset: KScreenWValue(5), // 文字向上偏移，下划线相对位置改变

          ]
          
          if let font = font {
              attributes[.font] = font
          }
          
          return NSAttributedString(string: self, attributes: attributes)
      }

//    /// 使用Kingfisher加载本地Bundle图片
//    func kingfisherBundleImage(ofType: String?) -> URL? {
//        let imagePath = Bundle.main.path(forResource: self, ofType: ofType)
//        if let path = imagePath {
//            return URL(fileURLWithPath: path)
//        }
//        return nil
//    }
    
}

extension NSAttributedString {
    var fullRange: NSRange {
        return NSRange(location: 0, length: self.length)
    }
}
